package com.xingshang.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xingshang.model.po.*;
import com.xingshang.model.vo.SearchVo;
import com.xingshang.service.AdminService;
import com.xingshang.service.CategoryService;
import com.xingshang.service.GoodsService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.List;

@Controller
@RequiredArgsConstructor
public class IndexController {

    private final GoodsService goodsService;
    private final CategoryService categoryService;
    private final AdminService adminService;

    @Value("${page.size}")
    private int PAGE_SIZE;


    @RequestMapping("/")
    public String index(
            Model model,
            HttpSession session,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(required = false) String searchName
    ) throws IOException {
        //判断是否以登陆
        User user = (User) session.getAttribute("user");

        if (user == null) {
            return "redirect:/user/login";
        }
        System.out.println("category:"+categoryId);
        Admin admin = adminService.findByAccount(user.getAccount());
        if (admin != null) {
            session.setAttribute("admin", admin);
            System.out.println(admin.getStatus());
        }
        SearchVo<GoodDoc> result = goodsService.search(categoryId,searchName, page, PAGE_SIZE);
        //获取总页数
        long totalPages = result.getTotal() % PAGE_SIZE == 0 ? result.getTotal() / PAGE_SIZE : result.getTotal() / PAGE_SIZE + 1;
        List<Goods> hotGoods = goodsService.selectHotAll();
        List<Category> categories = categoryService.list();
        //jstl
        model.addAttribute("goodsHotList", hotGoods);
        model.addAttribute("goodsNewList", result.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("categories", categories);
        session.setAttribute("user", user);
        return "index";
    }


}
